package com.bluefoxyu.protocol;

import com.bluefoxyu.common.Invocation;
import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpClient {
    private static final Logger log = LoggerFactory.getLogger(HttpClient.class);

    public String send(String hostname, Integer port, Invocation invocation) throws IOException {
        log.debug("Sending request to URL: http://{}:{}/", hostname, port);
        try {
            URL url = new URL("http", hostname, port, "/");
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);

            // 配置
            OutputStream outputStream = httpURLConnection.getOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(outputStream);

            oos.writeObject(invocation);
            oos.flush();
            oos.close();

            InputStream inputStream = httpURLConnection.getInputStream();
            return IOUtils.toString(inputStream);
        } catch (MalformedURLException e) {
            log.error("Malformed URL: {}", e.getMessage());
            throw e;
        } catch (IOException e) {
            log.error("IO Exception occurred: {}", e.getMessage());
            throw e;
        }
    }
}